import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sonora/bloc/login/sj_login_bloc.dart';
import 'package:sonora/bloc/login/sj_login_event.dart';
import 'package:sonora/bloc/login/sj_login_state.dart';
import 'package:sonora/config/sj_config.dart';
import 'package:sonora/services/sj_api_common_service.dart';
import 'package:sonora/shared/lib/constants/sj_colors.dart';
import 'package:sonora/utils/sj_log_utils.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/dialog/sj_privacy_dailog.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';

@RoutePage()
class SjLoginPage extends StatefulWidget {
  @override
  State<SjLoginPage> createState() => _SjLoginPageState();
}

class _SjLoginPageState extends State<SjLoginPage> {
  @override
  void initState() {
    // 隐藏状态栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky,
        overlays: []);
    super.initState();
  }

  @override
  void dispose() {
    // 还原系统 UI 模式
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SjLoginBloc(),
      child: Scaffold(
        body: Container(
          decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/launch.png'),
                  fit: BoxFit.cover)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Spacer(),
              Column(
                children: [
                  Image.asset(
                    'assets/images/logo.png',
                    height: 100,
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  const Text(
                    'Sonora',
                    style: SjTextStyle.customFontWhite24,
                  )
                ],
              ),
              const SizedBox(
                height: 222,
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 40),
                child: Column(
                  children: [
                    BlocBuilder<SjLoginBloc, SjLoginState>(
                      builder: (context, state) {
                        return Column(
                          children: [
                            // Apple 登录按钮
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: SjColors.themeColor,
                                onPrimary: Colors.black,
                                minimumSize: const Size(double.infinity, 54),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30),
                                ),
                              ),
                              onPressed: () {
                                if (state.useChecked) {
                                  context
                                      .read<SjLoginBloc>()
                                      .add(SjLoginEvent.appleLoginRequested(context));
                                } else {
                                  showDialog(
                                      context: context,
                                      builder: (BuildContext bContext) {
                                        return SjPrivacyDialog(
                                          title: 'Sonora',
                                          content:
                                              'By using our App you agree with our Term of Use and Privacy Policy.',
                                          onAgree: () {
                                            context.read<SjLoginBloc>().add(
                                                const SjLoginEvent.toggleUse(
                                                    useChecked: false));
                                            Navigator.of(bContext).pop();
                                            context.read<SjLoginBloc>().add(
                                                SjLoginEvent
                                                    .appleLoginRequested(context));
                                          },
                                          onCancel: () {
                                            Navigator.of(bContext).pop();
                                          },
                                        );
                                      });
                                }
                                SjLogPvManger.stat(
                                    page: SjLogPages.sjPageNameApplelogin);
                              },
                              child: Stack(
                                children: [
                                  Positioned(
                                    left: 32,
                                    top: 0,
                                    bottom: 0,
                                    child: Image.asset(
                                      'assets/images/apple_logo.png',
                                      height: 24,
                                    ),
                                  ),
                                  const Center(
                                    child: Text(
                                      'Sign in with Apple',
                                      style: SjTextStyle.customFontWhite16,
                                    ),
                                  )
                                ],
                              ),
                            ),
                            const SizedBox(height: 32),
                            // 快速登录按钮
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: SjColors.blackColor,
                                onPrimary: Colors.black,
                                minimumSize: const Size(double.infinity, 54),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30),
                                ),
                              ),
                              onPressed: () {
                                if (state.useChecked) {
                                  context.read<SjLoginBloc>().add(
                                      SjLoginEvent.fastLoginRequested(
                                          oauthType: 4, context: context));
                                } else {
                                  showDialog(
                                      context: context,
                                      builder: (BuildContext bContext) {
                                        return SjPrivacyDialog(
                                          title: 'Sonora',
                                          content:
                                              'By using our App you agree with our Term of Use and Privacy Policy.',
                                          onAgree: () {
                                            context.read<SjLoginBloc>().add(
                                                const SjLoginEvent.toggleUse(
                                                    useChecked: false));
                                            Navigator.of(bContext).pop();
                                            context.read<SjLoginBloc>().add(
                                                SjLoginEvent.fastLoginRequested(
                                                    oauthType: 4,
                                                    context: context));
                                          },
                                          onCancel: () {
                                            Navigator.of(bContext).pop();
                                          },
                                        );
                                      });
                                }
                                SjLogPvManger.stat(
                                    page: SjLogPages.sjPageNameQuicklogin);
                              },
                              child: Stack(
                                children: [
                                  Positioned(
                                    left: 32,
                                    top: 0,
                                    bottom: 0,
                                    child: Image.asset(
                                      'assets/images/lightning.png',
                                      height: 24,
                                    ),
                                  ),
                                  const Center(
                                    child: Text(
                                      'Fast Login',
                                      style: SjTextStyle.customFontTheme16,
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 48),
              // 用户协议复选框
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 40),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    BlocBuilder<SjLoginBloc, SjLoginState>(
                        builder: (context, state) {
                      return InkWell(
                        onTap: () {
                          context.read<SjLoginBloc>().add(
                              SjLoginEvent.toggleUse(
                                  useChecked: state.useChecked));
                        },
                        child: Container(
                          width: 16,
                          height: 16,
                          decoration: BoxDecoration(
                              image: DecorationImage(
                            image: state.useChecked
                                ? const AssetImage('assets/images/checked.png')
                                : const AssetImage('assets/images/check_circle.png'),
                            fit: BoxFit.cover,
                          )),
                        ),
                      );
                    }),
                    const SizedBox(width: 6),
                    Flexible(
                      // child: Text(
                      //   'By using our App you agree with our Terms of Use and Privacy Policy.',
                      //   style: TextStyle(color: Colors.white, fontSize: 12),
                      //   textAlign: TextAlign.left,
                      // ),

                      child: RichText(
                        textAlign: TextAlign.start,
                        text: TextSpan(
                            style: const TextStyle(
                                color: SjColors.textWhiteColor, fontSize: 12),
                            children: [
                              const TextSpan(
                                  text: 'By using our App you agree with our ',
                                  style: SjTextStyle.customFontWhite12),
                              TextSpan(
                                  text: 'Terms of Use',
                                  style: SjTextStyle.customFontTheme12,
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      context.router.push(SjWebviewRoute(
                                          url: userAgreement,
                                          title: 'Terms and Conditons'));
                                      SjLogPvManger.stat(
                                          page: SjLogPages.sjPageNameTerms);
                                    }),
                              const TextSpan(
                                  text: ' and ',
                                  style: SjTextStyle.customFontWhite12),
                              TextSpan(
                                  text: 'Privacy Policy.',
                                  style: SjTextStyle.customFontTheme12,
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      context.router.push(SjWebviewRoute(
                                          url: privacyAgreement,
                                          title: 'Privacy Policy'));
                                      SjLogPvManger.stat(
                                          page: SjLogPages.sjPageNamePrivacy);
                                    }),
                            ]),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 44),
            ],
          ),
        ),
      ),
    );
  }
}
